import { ElNotification } from 'element-plus'
import Zip from 'jszip';
import { saveAs } from 'file-saver';
import axios from 'axios';

/**
 * @description 接收数据流生成blob，创建链接，下载文件
 * @param {Function} api 导出表格的api方法(必传)
 * @param {String} tempName 导出的文件名(必传)
 * @param {Object} params 导出的参数(默认为空对象)
 * @param {Boolean} isNotify 是否有导出消息提示(默认为 true)
 * @param {String} fileType 导出的文件格式(默认为.xlsx)
 * @return void
 * */
export const downloadExternalFile = async (
  api,
  tempName,
  fileType = '.xlsx'
) => {
  try {
    const blobUrl = api
    const exportFile = document.createElement('a')
    exportFile.style.display = 'none'
    exportFile.href = blobUrl
    if (fileType) {
      exportFile.download = `${tempName}${fileType}`
    } else {
      exportFile.download = `${tempName}`
    }
    document.body.appendChild(exportFile)
    exportFile.click()
    // 去除下载对 url 的影响
    document.body.removeChild(exportFile)
    window.URL.revokeObjectURL(blobUrl)
  } catch (error) {
    throw Error(Error)
  }
}

export const downloadFile = async (
  api,
  tempName,
  is_split = true
) => {
  try {
    const response = await fetch(api, { method: 'GET' });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    // 检查并处理Content-Disposition，虽然这不是必须的，因为直接下载行为主要由后端控制
    const contentDisposition = response.headers.get('content-disposition');
    if (contentDisposition && !contentDisposition.includes('attachment')) {
      console.warn('The server did not specify the file as an attachment.');
    }
    if(is_split){
      const fileExtension = tempName.split('.').pop(); // 获取文件的后缀
      if(tempName.indexOf(fileExtension) > 0){
        tempName = tempName.substring(0, tempName.indexOf(fileExtension))
      }
    }
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const exportFile = document.createElement('a');
    exportFile.style.display = 'none';
    exportFile.href = url;
    exportFile.download = `${tempName}`;
    document.body.appendChild(exportFile);
    exportFile.click();
    document.body.removeChild(exportFile);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('Download failed:', error);
  }
}


export const batchDownload = (downloadUrl, fileName) => {
  // let downloadUrl = ['xxx', 'xxx', 'xxx']
  const zip = new Zip()
  const folder = zip.folder(fileName)
  const downloadTasks = downloadUrl.map(imageUrl => {
    return fetch(imageUrl).then(imageContent => {
      const name = imageUrl.split('/')[imageUrl.split('/').length - 1]
      // 写入二进制内容文件
      folder.file(name, imageContent.blob(), { binary: true })
    })
  })
  Promise.all(downloadTasks).then(() => {
    zip.generateAsync({ type: 'blob' }).then(content => {
      // 写入本地
      saveAs(content, fileName)
    })
  })
}

function getFile(url) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'GET',
      responseType: 'blob',
    })
      .then((data) => {
        resolve(data);
      })
      .catch((err) => {
        reject(err.toString());
      });
  });
}


// 仅支持视频下载和图片下载
export const downLoadImage = async (imageUrl) => {
  try {
    const blobUrl = `${imageUrl}?response-content-type=application/octet-stream`
    const fileName = 'downloaded-image.jpg'; // 下载后的文件名
    const exportFile = document.createElement('a')
    exportFile.style.display = 'none'
    exportFile.href = blobUrl
    exportFile.download = fileName
    exportFile.setAttribute('download', fileName);
    // const newWindow = window.open('', '_blank');
    // newWindow.document.body.appendChild(exportFile);
    // exportFile.click();
    // newWindow.close();
    // window.URL.revokeObjectURL(blobUrl);
    document.body.appendChild(exportFile)
    exportFile.click()
    // 去除下载对 url 的影响
    document.body.removeChild(exportFile)
    window.URL.revokeObjectURL(blobUrl)
  } catch (error) {
    throw Error(Error)
  }
}

export const downLoadExcel = async (blobUrl,fileName) => {
  try {
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = blobUrl;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(blobUrl);
  } catch (error) {
    throw Error(Error)
  }
}